package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private HotelMapper hotelMapper;
    @Autowired
    private RestHighLevelClient client;


    @Override
    public List<Hotel> findAll() {
        LambdaQueryWrapper<Hotel> queryWrapper = new LambdaQueryWrapper<>();
        List<Hotel> hotels = hotelMapper.selectList(queryWrapper);
        return hotels;
    }

    @Override
    public PageResult findHotel(RequestParams requestParams) {

        SearchRequest request = new SearchRequest("hotel");

        buildBasicQuery(requestParams,request);


        Integer page = requestParams.getPage();
        Integer size = requestParams.getSize();
        request.source().from((page-1)*size).size(size);

        String location = requestParams.getLocation();
        if (location != null && !location.equals("")) {
            request.source().sort(SortBuilders
                    .geoDistanceSort("location", new GeoPoint(location))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS)
            );
        }

        //高亮显示
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        SearchResponse search = null;
        try {
            search = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SearchHits searchHits = search.getHits();
        long total = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();

        List<HotelDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)){
                HighlightField name = highlightFields.get("name");
                String s = name.getFragments()[0].toString();
                hotelDoc.setName(s);
            }
            // 放入集合
            hotels.add(hotelDoc);
        }

        PageResult pageResult = new PageResult(total, hotels);

        return pageResult;
    }

    @Override
    public Map<String,List<String>> filters(RequestParams requestParams) {

        SearchRequest request = new SearchRequest("hotel");
        buildBasicQuery(requestParams,request);
        request.source().size(0);
        getAgg( request);
        Map<String, List<String>> map = new HashMap<>();
        SearchResponse search = null;
        try {
            search = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
            List<String> stars = getKey(search,"starAgg");
            List<String> brands = getKey(search,"brandAgg");
            List<String> city = getKey(search,"cityAgg");
            map.put("city",city);
            map.put("starName",stars);
            map.put("brand",brands);
        return map;
    }

    @Override
    public List<String> suggestion(String key) {

        SearchRequest request = new SearchRequest("hotel");
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "suggestion",
                SuggestBuilders.completionSuggestion("suggestion")
                .prefix(key)
                .skipDuplicates(true)
                .size(10)
        ));
        SearchResponse search = null;
        try {
            search = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        CompletionSuggestion suggestion = search.getSuggest().getSuggestion("suggestion");
        List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
        List<String> list = new ArrayList<>();
        for (CompletionSuggestion.Entry.Option option : options) {
            String text = option.getText().toString();
            list.add(text);
        }
        return list;
    }

    @Override
    public void deleteById(Long id) {
        try {
            DeleteRequest deleteRequest = new DeleteRequest("hotel",id.toString());
            client.delete(deleteRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insertById(Long id) {
        Hotel hotel = findId(id);

        HotelDoc hotelDoc = new HotelDoc(hotel);
        IndexRequest request = new IndexRequest("hotel").id(id.toString());

        JSON.toJSONString(hotelDoc);
        request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);
        try {
            IndexResponse index = client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {

        }

    }

    @Override
    public Hotel findId(Long id) {
        Hotel hotel = hotelMapper.selectById(id);
        return hotel;
    }

    private List<String> getKey( SearchResponse search,String name) {
        Terms aggregation = search.getAggregations().get(name);
        List<String> list = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = aggregation.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String brand = bucket.getKeyAsString();
            list.add(brand);
        }
        return list;
    }

    //聚合分组
    private void getAgg( SearchRequest request) {
            request.source().aggregation(AggregationBuilders.terms("brandAgg")
                    .field("brand")
                    .size(999));
            request.source().aggregation(AggregationBuilders.terms("cityAgg")
                    .field("city")
                    .size(999));
            request.source().aggregation(AggregationBuilders.terms("starAgg")
                    .field("starName")
                    .size(999));
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        // 1.构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 2.关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        // 3.城市条件
        if (params.getCity() != null && !params.getCity().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        // 4.品牌条件
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        // 5.星级条件
        if (params.getStarName() != null && !params.getStarName().equals("")) {
            String star =params.getStarName() ;
            if (params.getStarName().substring(1).equals("星")){
                star = params.getStarName()+ "级";
            }
            boolQuery.filter(QueryBuilders.termQuery("starName", star));
        }
        // 6.价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice())
            );
        }
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQuery,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });


        // 7.放入source
        request.source().query(functionScoreQuery);
    }



}
